<template>
	<!-- 任务列表 -->
	<view class="page">
		<uv-navbar title="检查记录" auto-back placeholder />
		<view class="list ss-r-20 ss-shadow">
			<view class="ss-grey-2 ss-w-100 ss-font-28">
				<view class="list_tit ss-flex ss-p-x-36 ss-p-y-26">
					<view class="des">检测项目</view>
					<view class="ss-m-x-20 ss-black ss-flex-1">{{ state.name || "-" }}</view>
				</view>
				<view class="ss-flex ss-p-x-36 ss-col-top ss-p-y-26 req">
					<view class="des">测试方法和要求</view>
					<view class="ss-m-x-20 ss-black ss-flex-1">
						{{ state.specification || "-" }}
					</view>
				</view>
			</view>
			<g-tabs-top :list="tabList" v-model:current="state.currentTab" sticky top="44px" keyName="name"
				:scroll="false" @change="changeTab" />
			<view class="ss-p-26 ss-bg-w ss-font-28" v-if="state.currentTab == 0">
				<view class="ss-flex ss-col-center ss-m-y-10">
					<view class="tabCard_l"></view>
					<view class="ss-m-x-10 ss-black">基本信息</view>
				</view>
				<view class="ss-grey-2 ss-m-x-6 ss-m-y-16">
					<view class="ss-m-y-16"> 已检查数量 （不允许修改） </view>
					<uv-input placeholder="请输入内容" border="surround" v-model="state.completedCount" disabled />
				</view>
				<view class="ss-grey-2 ss-m-x-6 ss-m-y-16">
					<view class="ss-m-y-16"><text style="color: red;">
							*
						</text> 检查数量（应完成{{ state.allowTotal }} 剩余 {{ state.total - state.completedCount }}） </view>
					<uv-input placeholder="输入数量" border="surround" type="number" v-model="checkDetails.inspectCount" />
				</view>
				<view class="ss-grey-2 ss-m-x-6 ss-m-y-16">
					<view class="ss-m-y-16"> <text v-if="checkDetails.status == 2" style="color: red;">
							*
						</text> 问题描述 </view>
					<g-select v-model:value="problemId" :list="problemList" key-value="id" mode="checkbox"
						key-name="problemContent" title="选择问题" placeholder="请选择问题" @change="changeProblem" />
					<uv-textarea v-if="problemId == -1" v-model="checkDetails.problemDescription"
						placeholder="请填写问题描述" />
				</view>
				<view class="ss-grey-2 ss-m-x-6 ss-m-y-16">
					<view class="ss-m-y-16"> 位置描述 </view>
					<uv-input placeholder="请填写位置描述" border="surround" v-model="checkDetails.locationDescription" />
				</view>
				<view class="ss-flex ss-col-center ss-m-y-10">
					<view class="tabCard_l"></view>
					<view class="ss-m-x-10 ss-black">检查结果 (必填)</view>
				</view>
				<view class="ss-flex ss-col-center ss-m-y-10">
					<view>
						<uv-radio-group>
							<uv-radio :customStyle="{
                  border:
                    checkDetails.status == item.id
                      ? '2px soild #4EA770'
                      : '2px soild #DCDFE6',
                }" v-for="(item, index) in resList" :key="index" :label="item.name" :name="item.name"
								@change="changeRadio(item.id)" activeColor="#4EA770">
							</uv-radio>
						</uv-radio-group>
					</view>
				</view>
				<view class="ss-grey-2 ss-m-x-6 ss-m-y-16">
					<view class="ss-m-y-16"> 备注 </view>
					<uv-textarea v-model="checkDetails.remark" />
				</view>
				<view class="ss-grey-2 ss-m-x-6 ss-m-y-16">
					<view class="ss-m-y-16"> <text style="color: red;">
							*
						</text>
						上传照片 </view>
					<Task-upload
						v-model:value="state.imgUrl"
						:offline-mode="state.offlineMode"
						:max="9"
						address-mark
						time-mark
						multiple
						@state="upLoadState" />
				</view>
				<view class="btn-box">
					<uv-button text="提交" type="primary" shape="circle" color="#4EA770" :throttle-time="1000"
						:custom-style="{width: '100%'}" @click="handleSubmit" />
				</view>
			</view>
			<view v-if="state.currentTab == 1" class="ss-bg-w">
				<g-steps :steps="dataList" direction="column" slot-class=".step-remark" :current="4" stepsId="checkId"
					key-name="day">
					<template v-for="(i, k) in dataList" :key="k" #[i.slot]="{ scope }">
						<view class="step-remark" @click="toDetail(i.id)">
							<view class="step-row ss-col-center">
								<view class="step-row-left">
									<view class="ss-flex ss-flex-1">
										<view class="operator">{{ scope.inspectUserNickName || "-" }}</view>
										<view class="post-tag">
											{{ enumUserType(scope.inspectUserType) }}
										</view>
									</view>
									<view class="ss-m-y-14"> 检查数量：{{ scope.inspectCount }} </view>
								</view>
								<uv-avatar :src="scope.inspectUserAvatar" size="106rpx"
									:customStyle="{ padding: '20rpx', paddingBottom: '0' }" />
							</view>
							<view class="step-bottom">
								<uv-text :text="`检查结果：${scope.status == '1' ? '合格' : '不合格'}`" color="#757575"
									size="24rpx" margin="10rpx 0" />
								<uv-text :text="scope.createTime" color="#757575" size="24rpx" />
							</view>
							<view v-if="scope.isOffline == 1" class="step-offline" />
						</view>
					</template>
				</g-steps>
				<view class="more ss-p-y-10 ss-font-28 ss-grey-2" v-if="dataList.length != 0" @click="goMore">
					{{ state.isText }}
				</view>
				<uv-empty v-if="dataList.length === 0" :customStyle="{ padding: '10vh 0' }" :icon="empty" text="暂无记录" />

			</view>
			<view v-if="state.currentTab == 2" class="ss-bg-w ss-p-30" style="text-align: center">
				<view class="tabBox" v-if="videoName.length!=0">
					<uv-scroll-list :indicator="false">
						<view class="ss-flex">
							<view class="tab_list ss-font-28 ss-p-16" v-for="(i,index) in videoName" :key="index"
								:style="{color:state.currentVideo == index?'#fff':'#000',background:state.currentVideo == index?'#4EA770':'#fff'}"
								@click="changeVideo(index)">
								<view>
									{{i}}
								</view>
							</view>
						</view>
					</uv-scroll-list>
				</view>
				<video :src="webSrc(videoList[state.currentVideo])" v-if="videoList.length!=0" />
				<uv-empty v-if="videoList.length == 0" margin-top="2vh" :icon="empty" :text="`暂无视频`" />
				<view class="videoGuidanceSty"> {{ checkDetails.videoGuidance || "-" }} </view>
			</view>
		</view>

		<view
			v-if="userInfo?.userType == '03'"
			class="add-icon ss-bg-w ss-flex ss-row-center ss-font-26"
			@click="Jump"
			@touchmove.stop.prevent="touchmove"
			:style="{
				top: state.moveY + 'px',
				right: isCollapse ? '-104rpx' : 0,
			}
		">
			<uv-icon :name="iconCreate" size="26rpx" label="新建工单" label-size="24rpx" :label-color="isCollapse ? 'transparent' : '#212121'" />
		</view>
	</view>
	<vv-dialog v-model:projectType="state.projectType" :count="state.total - state.completedCount" :type="state.type" />
</template>
<script setup>
	import {
		reactive,
		ref,
		onMounted,
	} from "vue";
	import {
		onLoad,
		onBackPress,
		onPageScroll
	} from "@dcloudio/uni-app";
	import {
		deviceDetail,
		deviceItem,
		recordAdd,
		recordList,
		getProblemData
	} from "@/request/task.js";
	import {
		webSrc,
		timeFormat,
		enumUserType,
	} from "@/common/mothed.js";
	import EventBus from "@/request/eventBus.js";
	import { checkNetwork } from "@/request/common.js";
	import TaskUpload from "@/pages/Task/cp/TaskUpload.vue"
	import vvDialog from "@/components/Dialog/Dialog.vue"
	import iconCreate from "@/static/order/icon_create.png";
	import empty from "@/static/empty.png";

	const checkDetails = ref({
		inspectCount: "",
		problemDescription: "",
		locationDescription: "",
		remark: "",
		status: "",
		imgUrl: "",
		videoGuidance: ""
	});
	const isCollapse = ref(false); // 是否折叠按钮
	const total = ref(0); // 总条数
	const queryParams = ref({
		deviceTasksItemId: "",
		pageNum: 1, // 页数
		pageSize: 10, // 条数
	});
	const tabList = ref([
		{ id: 0, name: "任务填报" },
		{ id: 1, name: "检查记录" },
		{ id: 2, name: "视频指导" },
	]);

	const resList = ref([
		{ id: 1, name: "合格" },
		{ id: 2, name: "不合格" },
	]);
	const unBack = ref(false); // 阻止放行
	const disabled = ref(false); // 禁止提交

	const videoList = ref([]);
	const videoName = ref([]);
	const dataList = ref([]);
	const problemList = ref([]); // 问题列表
	const problemId = ref(); // 临时问题id
	const userInfo = ref({}); // 用户信息

	const state = reactive({
		currentVideo: 0,
		id: "",
		currentTab: 0,
		completedCount: 0,
		type: "MONTH", // 检查项周期类型
		taskItemId: "",
		specification: "",
		name: "",
		isText: "",
		imgUrl: [],
		projectType: 0,
		isFinish: false,
		total: 0,
		allowTotal: 0,
		systemId: '',
		deviceId: '',
		floorDeviceId: "",
		deviceName: "",
		moveY: null,
		startY: 0,
		offlineMode: false,
	});

	onLoad(async (e) => {
		queryParams.value.deviceTasksItemId = e.taskItemId;
		checkDetails.value.deviceTasksItemId = e.taskItemId;
		state.taskItemId = e.taskItemId;
		state.deviceId = e.deviceId;
		state.deviceName = decodeURIComponent(e.deviceName);
		state.id = e.id;
		state.systemId = e.systemId;
		state.floorDeviceId = e.floorDeviceId;
		state.completedCount = parseInt(e.completedCount) || 0;
		state.type = e.type;
		state.total = parseInt(e.total) || 0;
		state.allowTotal = parseInt(e.allowTotal) || 0;

		let info = uni.getStorageSync("userInfo");
		if (info) userInfo.value = info;
		const network = await checkNetwork(); // 检查网络
		if (network == "none") {
			state.offlineMode = true;
			let detail = uni.getStorageSync('offline-task-detail');
			if (detail) {
				state.name = detail.deviceItem?.name;
				state.specification = detail.deviceItem?.specification;
				problemList.value = detail.problemList || [];
				problemList.value.push({
					id: -1,
					problemContent: '其它'
				})
			}
		} else {
			getDetails();
			getProblems();
		}
	});

	onMounted(() => {
		uni.$on("network-change", (status) => {
			if (status == "none") {
				state.offlineMode = true;
				let detail = uni.getStorageSync('offline-task-detail');
				if (detail) {
					state.name = detail.deviceItem?.name;
					state.specification = detail.deviceItem?.specification;
					problemList.value = detail.problemList || [];
					problemList.value.push({
						id: -1,
						problemContent: '其它'
					})
				}
			} else {
				state.offlineMode = false;
			}
		});
	})

	onPageScroll((e) => {
		isCollapse.value = e.scrollTop > 40;
	});

	onBackPress((e) => {
		if (unBack.value) {
			uni.showModal({
				title: "退出确认",
				content: "有文件尚未提交成功，是否取消？",
				showCancel: true,
				confirmColor: "#4EA770",
				success: ({
					confirm
				}) => {
					if (confirm) {
						unBack.value = false;
						uni.navigateBack();
					}
				},
			});
		}
		return unBack.value; //阻止返回
	});

	// 监听上传状态
	const upLoadState = (val) => {
		unBack.value = val.noBack;
		console.log('上传动态：', val);
		disabled.value = val.state != 'success';
	}

	// 提交检查记录
	const handleSubmit = async () => {
		if (checkDetails.value.inspectCount == "" || checkDetails.value.inspectCount == 0) {
			uni.showToast({
				title: "请填写检查数量",
				icon: "none",
			});
			return;
		}
		if (parseInt(checkDetails.value.inspectCount || '0') < 0) {
			uni.showToast({
				title: "请正确填写数量",
				icon: "none",
			});
			return;
		}
		if (state.completedCount + parseInt(checkDetails.value.inspectCount || '0') > state.total) {
			state.projectType = 4
			return;
		}
		if (checkDetails.value.status == "") {
			uni.showToast({
				title: "请选择检查结果",
				icon: "none",
			});
			return;
		}
		if (checkDetails.value.status == 2 && checkDetails.value.problemDescription == "") {
			uni.showToast({
				title: "请输入问题描述",
				icon: "none",
			});
			return;
		}
		if (state.imgUrl.length == 0) {
			uni.showToast({
				title: "请上传检查照片",
				icon: "none",
			});
			return;
		}
		if (disabled.value) {
			uni.showToast({
				title: "请照片上传完成再提交",
				icon: "none",
			});
			return;
		}
		if (state.offlineMode) {
			let data = Object.assign({}, checkDetails.value);
			let list = uni.getStorageSync('offline-task-submit');
			let build = uni.getStorageSync('offline-task-build') || {};
			data.buildingName= build.buildingName;
			data.buildingFloorName = build.floor;
			data.deviceName = state.deviceName;
			data.deviceItemName = state.name;
			data.isOffline = 1;
			data.completeTime = timeFormat(Number(new Date()), "yyyy-mm-dd hh:MM:ss")
			data.imgUrl = state.imgUrl || [];
			if (list) {
				list.push(data);
			} else {
				list = [data];
			}
			uni.setStorage({
				key: "offline-task-submit",
				data: list,
				success: () => {
					unBack.value = false;
					updateOfflineTask(build);
					uni.showToast({
						title: '已提交到离线任务',
						icon: "none",
						duration: 2000,
						success: () => {
							setTimeout(() => {
								uni.navigateBack({
									delta: 1
								});
							}, 2000);
						}
					})
					EventBus.emit("offlineChange", {key: 'offline-task-submit', data: list, isFinish: false });
				},
				fail: () => {
					uni.showToast({
						title: '文件过大超过缓存限制',
						icon: "none",
					})
				}
			});
		} else {
			checkDetails.value.imgUrl = state.imgUrl.join(",");
			recordAdd(checkDetails.value).then((res) => {
				if (res.code == 200) {
					//任务选择刷新
					uni.$emit("listSelectStateTask");
					state.isFinish = res.data.isFinish
					problemId.value = null;
					if (state.isFinish) {
						state.projectType = 3
					} else {
						uni.showToast({
							title: res.msg,
							icon: "none",
						});
					}
					resetForm();
					unBack.value = false;
					state.currentTab = 1;
					changeTab({
						id: 1
					})
				}
			});
		}
	};

	// 更新离线数据数量
	const updateOfflineTask = (build) => {
		let list = uni.getStorageSync('offline-task-cache');
		let statistics = uni.getStorageSync('offline-task-device');
		list.forEach(b => {
			// 楼栋
			if (b.buildingId == build.buildingId) {
				b?.floors.forEach(f => {
					// 楼层
					if (f.floorId == build.floorId) {
						f?.systemDtoList.forEach(s => {
							// 系统
							if (s.systemId == state.systemId) {
								s?.deviceTasksList.forEach(d => {
									// 设备
									if (d.id == state.floorDeviceId) {
										d?.tasksItemList.forEach(t => {
											// 检查项
											if (t.taskItemId == state.taskItemId) {
												t.completedCount += parseInt(checkDetails.value.inspectCount || '0');
											}
										})
										let minNum = 0;
										d?.tasksItemList.forEach((t, i) => {
											if (i == 0) minNum = t.completedCount;
											if (t.completedCount <= minNum)	minNum = t.completedCount;
										})
										if (d.completedCount != minNum) {
											let differ = minNum - d.completedCount;
											d.completedCount = minNum; // 修改设备已完成
											d.deviceRemainTotal -= differ; // 修改设备剩余数量
											s.completedCount += differ; // 修改系统已完成
											s.deviceRemainTotal -= differ; // 修改系统剩余数量
											// 修改项目该设别已完成数
											let num = statistics[d.deviceId];
											if (num - differ > 0) {
												statistics[d.deviceId] = num - differ;
											} else {
												delete statistics[d.deviceId];
											}
											uni.setStorageSync('offline-task-device', statistics);
										}
									}
								})
							}
						})
					}
				})
			}
		});
		uni.setStorageSync('offline-task-cache', list);
	}

	// 重置表单
	const resetForm = () => {
		checkDetails.value.inspectCount = 0;
		checkDetails.value.problemDescription = "";
		checkDetails.value.locationDescription = "";
		checkDetails.value.status = null;
		checkDetails.value.remark = "";
		checkDetails.value.imgUrl = '';
		state.imgUrl = [];
	}

	// 新建工单
	const Jump = () => {
		if (isCollapse.value) {
			isCollapse.value = false;
			return;
		}
		if (state.offlineMode) {
			uni.showToast({
				title: "离线模式无法操作",
				icon: "none",
			});
			return;
		}
		uni.navigateTo({
			url: "/pages/Order/addOrder",
		});
	};

	// 拖动按钮
	const touchmove = (e) => {
		const touch = e.touches[0];
		state.moveY += touch.clientY - state.startY;
		state.startY = touch.clientY;
		const screenHeight = uni.getSystemInfoSync().windowHeight;
		const maxHeight = screenHeight - 40;
		if (state.moveY > maxHeight) {
			state.moveY = maxHeight;
			state.startY = maxHeight;
		} else if (state.moveY < 0) {
			state.moveY = 0;
			state.startY = 0;
		}
	}

	// 是否合格
	const changeRadio = (e) => {
		checkDetails.value.status = e;
	};

	// 获取常见问题列表
	const getProblems = () => {
		getProblemData({
			pageNum: 1,
			pageSize: 1000,
			systemId: state.systemId,
			deviceId: state.deviceId,
			deviceItemId: state.id
		}).then(res => {
			problemList.value = res.rows;
			problemList.value.push({
				id: -1,
				problemContent: '其它'
			})
		})
	}

	// 选择问题
	const changeProblem = (val) => {
		console.log('选择问题', val, problemId.value)
		if (val.value.includes(-1)) {
			problemId.value = [-1];
			checkDetails.value.problemDescription = '';
		} else {
			checkDetails.value.problemDescription = val.label.join(',');
		}
	}

	// 记录详情
	const getDetails = () => {
		deviceItem(state.id).then((res) => {
			if (res.code == 200) {
				state.name = res.data.name;
				state.specification = res.data.specification;
			}
		});
	};

	// 获取视频
	const getVideo = () => {
		deviceDetail(state.deviceId).then((res) => {
			if (res.code == 200) {
				videoList.value = res.data.referenceVideo ? res.data.referenceVideo.split(',') : []
				videoName.value = res.data.referenceVideoName ? res.data.referenceVideoName.split(',') : []
				checkDetails.value.videoGuidance = res.data.videoGuidance
			}
		});
	};

	// 记录列表
	const getList = () => {
		recordList(queryParams.value).then((res) => {
			if (res.code == 200) {
				let arr = res.rows.map((i, k) => {
					return {
						...i,
						slot: "step" + (k + 1),
						day: timeFormat(Number(new Date(i.createTime)), "mm-dd"),
					};
				});
				dataList.value = queryParams.value.pageNum == 1 ? arr : dataList.value.concat(arr);
				total.value = res.total;
				if (res.total >= dataList.value.length) {
					state.isText = "暂无更多";
				} else {
					state.isText = "点击加载";
				}
			}
		});
	};

	// 切换模块
	const changeTab = (e) => {
		if (e.id != 0 && state.offlineMode) {
			uni.showToast({
				title: "离线模式无法查看",
				icon: "none",
			});
			state.currentTab = 0;
			return;
		}
		if (e.id == 1) {
			queryParams.value.pageNum = 1;
			getList();
		} else if (e.id == 2) {
			getVideo();
		}
	};

	// 选择视频
	const changeVideo = (e) => {
		state.currentVideo = e
	};
	
	const toDetail = (id) => {
		uni.navigateTo({
			url: `/pages/Task/recordDetails?recordId=${id}&name=${state.name}&specification=${state.specification}`
		})
	};


	// 加载更多
	const goMore = () => {
		if (total.value == dataList.value.length) return;
		page.value++;
		getList();
	};
</script>
<style lang="scss" scoped>
	@import "@/uni.scss";

	.more {
		text-align: center;
	}

	.page {
		padding: 30rpx;
	}

	.videoGuidanceSty {
		text-align: left;
		font-size: 28rpx;
		margin-left: 10rpx;
	}


	.tabBox {
		display: flex;
		justify-content: space-between;
		width: 100%;
		padding: 10rpx 20rpx 0;
		box-sizing: border-box;
		text-align: left;
		font-size: 30rpx;
		overflow-x: auto;

		.tab_list {
			min-width: 80rpx;
			padding: 10rpx 20rpx;
			margin-right: 20rpx;
			border-radius: 10rpx;
			text-align: center !important;
		}
	}

	.step-remark {
		position: absolute;
		left: 50rpx;
		top: 60rpx;
		background: #fff;
		border-radius: 20rpx;
		border: 2rpx solid #dedede;
		box-sizing: border-box;
		width: 580rpx;
		height: 260rpx;

		.step-row {
			display: flex;
			justify-content: space-between;

			&-left {
				max-width: 410rpx;
				flex: 1;
				padding: 20rpx 0 20rpx 20rpx;
				padding-bottom: 0;

				.operator {
					font-size: 36rpx;
					color: #212121;
					overflow: hidden;
					text-overflow: ellipsis;
					white-space: nowrap;
				}

				.post-tag {
					min-width: 220rpx;
					font-size: 24rpx;
					color: #757575;
					margin-left: 30rpx;
					overflow: hidden;
					text-overflow: ellipsis;
					white-space: nowrap;
				}

				.step {
					color: #4ea770;
					font-size: 24rpx;
					margin-top: 20rpx;
					display: inline-block;
					padding: 6rpx 20rpx;
					background: #e6f1e9;
					border-radius: 8rpx;
					border: 2rpx solid #abd49d;
				}

				.red {
					color: #eb736c;
					background: #fbeeee;
					border: 1px solid #e3a0a0;
				}
			}
		}

		.step-bottom {
			padding: 20rpx;
			padding-top: 0;
		}
		.step-offline {
			position: absolute;
			right: 0;
			top: 0;
			height: 100%;
			width: 40%;
			background: linear-gradient(to right, transparent, rgba(219, 219, 219, 0.5));
			border-top-right-radius: 20rpx;
			border-bottom-right-radius: 20rpx;
			&::after {
				content: "离线提交";
				position: absolute;
				right: 20rpx;
				bottom: 20rpx;
				color: #828282;
			}
		}
	}

	.add-icon {
		width: 174rpx;
		position: fixed;
		bottom: 104rpx;
		height: 70rpx;
		z-index: 100;
		transition: right 0.5s;
		box-shadow: 0 0 30rpx 2rpx rgba(0, 0, 0, 0.16);
		border-radius: 12rpx 0 0 12rpx;
	}

	.list {
		width: 100%;

		.req {
			max-height: 340rpx;
			overflow-y: auto;
		}

		.list_tit {
			border-bottom: 2rpx solid gainsboro;
		}

		.des {
			width: 140rpx;
			text-align: center;
		}

		.radioBox {
			border: 2rpx soild goldenrod;
			width: 160rpx;
			height: 100rpx;
		}
	}

	.btn-box {
		position: sticky;
		bottom: 0;
		left: 0;
		right: 0;
		padding: 20rpx;
		background-color: #fff;
		border-top: 1px solid #f5f5f5;
		margin-top: 20rpx;
		z-index: 9;
	}

	:deep() {
		.uv-radio {
			border: 2rpx solid #dcdfe6;
			padding: 20rpx 40rpx;
			border-radius: 10rpx;
			margin: 20rpx 80rpx;
			margin-right: 20rpx;
		}
	}
</style>